package com.app.system.config.shiro;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;

/**
 * 密码生成器
 */
@Slf4j
public class GenerateCipherKey {
    /**
     * 随机生成秘钥，参考org.apache.shiro.crypto.AbstractSymmetricCipherService#generateNewKey(int)
     *
     * @return 随机生成秘钥
     */
    @Bean
    public static byte[] generateNewKey() {

        KeyGenerator keyGenerator;

        try {
            keyGenerator = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            String msg = "Unable to acquire AES algorithm. This is required to function.";
            throw new IllegalStateException(msg, e);
        }

        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] encoded = secretKey.getEncoded();

        log.info("生成随机秘钥成功！");

        return encoded;
    }
}
